package com.fc.incross_server.filter;

import com.fc.incross_server.engine.Server;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.*;

/**
 * @Author: GY.
 * @Description: TODO()
 * @Date:Created in 2020/2/24 0024.
 * @Modified By:
 */
@Component
public class ServerRequestFilter implements Filter {
    public static volatile Map<String, byte[]> requestByteMap = new HashMap<>(1024);
//    public static volatile List<byte[]> requestByte = new ArrayList<>();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("=================RequestFilter==================");
        ServletInputStream inputStream = servletRequest.getInputStream();
        byte[] bytes = new byte[4096];
        inputStream.read(bytes);
        String uuid = UUID.randomUUID().toString();
        requestByteMap.put(uuid,bytes);
        synchronized ("requestByteMap"){
            "requestByteMap".notifyAll();
        }
        Map<String, byte[]> responseByteMap = Server.responseByteMap;
        while (responseByteMap.size() == 0 || responseByteMap.get(uuid) == null){
            synchronized (uuid) {
                try {
                    uuid.wait();
                    continue;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        byte[] bytes1 = responseByteMap.get(uuid);
        String s = new String(bytes1, "utf-8");
        String trim = s.trim();
        bytes1 = trim.getBytes("utf-8");
        servletResponse.setContentType("application/json");
        ServletOutputStream outputStream = servletResponse.getOutputStream();
        outputStream.write(bytes1);
        requestByteMap.remove(uuid);
        outputStream.flush();

        // 等待 响应
//        ServletOutputStream outputStream = servletResponse.getOutputStream();
//        outputStream.print("error");
//        outputStream.flush();
        // 过
//        filterChain.doFilter(servletRequest,servletResponse);
    }
}
